<template>
  <div v-has="'user-query'" class="user-manager">
    <div class="query-form">
      <query-form
        :form="searchForm"
        v-model="user"
        @handleQuery="handleQuery"
        @handleReset="handleReset"
      />
    </div>

    <div class="base-table">
      <list-table
        :columns="columns"
        :tableList="tableList"
        :selectionShow="selectionShow"
        :btnList="btnList"
        @userCreate="userCreate"
        @userDelete="userDelete"
        @onuserEdit="onuserEdit"
        @userDel="userDel"
      />
      <pagination :total="total" @handleCurrentChange="handleCurrentChange" />

      <!-- <div class="action">
        <el-button type="primary" v-has="'user-create'" @click="userCreate"
          >新增</el-button
        >
        <el-button type="danger" v-has="'user-patch-delete'" @click="batchDel"
          >批量删除</el-button
        >
      </div>

      <el-table
        ref="multipleTableRef"
        :data="userList"
        style="width: 100%"
        @select="select"
        @select-all="selectAll"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :formatter="item.formatter"
          width="200"
        ></el-table-column>
        <el-table-column label="操作" width="160">
          <template #default="scope">
            <el-button
              type="primary"
              v-has="'user-edit'"
              @click="edit(scope.row)"
              >编辑</el-button
            >
            <el-popconfirm
              confirm-button-text="Yes"
              cancel-button-text="No"
              title="Are you sure to delete?"
              @confirm="del(scope.row)"
            >
              <template #reference>
                <el-button type="danger" v-has="'user-delete'">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div class="page">
        <el-pagination
          layout=" prev, pager, next"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </div> -->
    </div>

    <el-dialog v-model="showMadol" :title="title">
      <el-form ref="createUserForm" :rules="rules" :model="form">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input v-model="form.userEmail" autocomplete="off" />
        </el-form-item>
        <el-form-item label="号码" prop="mobile">
          <el-input v-model="form.mobile" autocomplete="off" />
        </el-form-item>
        <el-form-item label="岗位" prop="job">
          <el-input v-model="form.job" autocomplete="off" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="form.state" placeholder="状态">
            <el-option label="在职" :value="1" />
            <el-option label="离职" :value="2" />
            <el-option label="试用期" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="系统角色" prop="roleList">
          <el-select
            v-model="form.roleList"
            multiple
            placeholder="请选择用户角色"
            style="width: 100%"
          >
            <el-option
              v-for="item in roleList"
              :key="item._id"
              :label="item.roleName"
              :value="item._id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-cascader
            v-model="form.deptId"
            :options="deptList"
            placeholder="请选择你的部门"
            :props="{ checkStrictly: true, value: '_id', label: 'deptName' }"
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// CURD 增删改查 不需要制作炫酷的交互 关注数据的逻辑处理
import api from './../api'
import message from '../utils/message.js'
import { ElMessageBox } from 'element-plus'
import { ref, reactive, nextTick, toRaw } from 'vue'
import utils from './../utils/utils.js'
// 显示按钮
let btnList = reactive({
  tbTopBtn: [
    {
      type: 'primary',
      text: '新增',
      id: 1,
      has: 'user-create',
    },
    {
      type: 'danger',
      text: '批量删除',
      id: 0,
      has: 'user-patch-delete',
    },
  ],
  tableBtn: [
    {
      type: 'primary',
      text: '编辑',
      id: 3,
      has: 'user-edit',
    },
    {
      type: 'danger',
      text: '删除',
      id: 2,
      has: 'user-delete',
    },
  ],
})
// 复选框显示
let selectionShow = ref(true)
// 显示搜索表单
const searchForm = [
  {
    type: 'input',
    label: '用户名Id',
    prop: 'userId',
    placeholder: '请输入用户ID'
  },
  {
    type: 'input',
    label: '用户名',
    prop: 'userName',
    placeholder: '请输入用户名'
  },
  {
    type: 'select',
    label: '状态',
    prop: 'state',
    placeholder: '状态',
    option: [
      {
        value: 0,
        label: '所有'
      },
      {
        value: 1,
        label: '在职'
      },
      {
        value: 2,
        label: '离职'
      },
      {
        value: 3,
        label: '试用期'
      },
    ]
  },
]
// 定义显示页码数
let total = ref(10)
// 定义用户行为初始化
const action = ref('add')
// 定义检验规则
let rules = reactive({
  userName: {
    required: true,
    message: '请输入用户名',
    trigger: 'blur'
  },
  userEmail: {
    required: true,
    message: '请输入邮箱',
    trigger: 'blur'
  },
  userPhone: [
    {
      pattern: /1[3-9]\d{9}/,
      required: true,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ]
})
// 定义新增用户弹窗节点
let createUserForm = ref(null)
// 定义角色列表
let roleList = ref([])
// 定义部门列表
let deptList = ref([])
// 定义弹窗
let showMadol = ref(false)
// 定义弹窗title
let title = ref('新增用户')
// 定义新增模块用户
let form = reactive({
  state: 3
})
// 定义动态表格--格式
let columns = reactive([
  {
    label: '用户ID',
    prop: 'userId'
  },
  {
    label: '用户名',
    prop: 'userName'
  },
  {
    label: '用户邮箱',
    prop: 'userEmail'
  },
  {
    label: '用户角色',
    prop: 'role',
    formatter (row, colum, value) {
      return {
        0: '管理员',
        1: '普通用户',
      }[value]
    }
  },
  {
    label: '用户状态',
    prop: 'state',
    formatter (row, colum, value) {
      return {
        1: '在职',
        2: '离职',
        3: '试用期'
      }[value]
    }
  },
  {
    label: '注册时间',
    prop: 'createTime',
    formatter: (row, colum, value) => {
      return utils.formateDate(new Date(value))
    }
  },
  {
    label: '最后登录时间',
    prop: 'lastLoginTime',
    formatter: (row, colum, value) => {
      return utils.formateDate(new Date(value))
    }
  },
])
// 定义初始化用户分类
let user = reactive({
  state: 1
})
// 定义初始化的分页设置
let pager = reactive({
  pageNum: 1,
  pageSize: 10
})
// 定义用户列表
const tableList = ref([])
// 获取用户列表请求
const getUsersList = async () => {
  let data = { ...user, ...pager }
  let { list, page } = await api.getUsersList(data)
  tableList.value = list
  total.value = page.total
}
// 获取角色名称列表请求
const getRolesAllList = async () => {
  roleList.value = await api.getRolesAllList()
}
// 获取部门列表请求
const getDeptList = async () => {
  deptList.value = await api.getDeptList()
}
// 管理页面数据初始化请求
getUsersList()
getRolesAllList()
getDeptList()
// 新增
const userCreate = (val) => {
  action.value = 'add'
  showMadol.value = val.showMadol
}
// 弹窗取消
const handleCancel = () => {
  resetForm()
  showMadol.value = false
}
// 弹窗确定
const handleSubmit = () => {
  createUserForm.value.validate((vaild) => {
    if (vaild) {
      // 发送请求
      let data = toRaw(form)
      //   form是响应式对象
      //   data 是只需要一个普通对象
      // 需要把响应式对象变成普通对象
      data.action = action.value
      api.postUsersOperate(data).then(res => {
        // 弹窗关闭
        showMadol.value = !showMadol.value
        // 重新发送获取用户列表请求出现渲染数据
        message.message('提交成功!', 'success')
        getUsersList()
      })
    }
  })
}
// 重置表单
const resetForm = () => {
  createUserForm.value.resetFields()
  handleReset()
}
// 编辑
const onuserEdit = (row) => {
  title.value = '编辑用户'
  action.value = 'edit'
  showMadol.value = !showMadol.value
  nextTick(() => {
    Object.assign(form, row.row)
  })
}
// 单删除
const userDel = (row) => {
  if (row.state == 2) {
    message.message('该用户状态不能删除!', 'warning')
  } else {
    api.postUsersDelete({ userIds: row.userId }).then(res => {
      message.message('删除成功!', 'success')
      getUsersList()
    })
  }
}
// 批量删除
const userDelete = (val) => {
  if (val.length == 0) {
    message.message('请选择用户!')
  } else {
    ElMessageBox.confirm(
      'Delete the selected?',
      'Tips',
      {
        confirmButtonText: 'Yes',
        cancelButtonText: 'No',
        type: 'Tips',
      }
    )
      .then(() => {
        api.postUsersDelete({ userIds: val }).then(res => {
          message.message('删除成功!', 'success')
          getUsersList()
        })
      })
  }
}
// 查询
const screeningUser = () => {
  let data = toRaw({ ...form, ...pager })
  //   data.state = searchForm[3].value
  api.getUsersList(data).then(res => {
    userList.value = res.list
    message.message('查询成功!', 'success')
  })
}
// 分页切换
const handleCurrentChange = async (val) => {
  let data = { ...user, ...pager }
  data.pageNum = val
  let { list } = await api.getUsersList(data)
  tableList.value = list
}
// 查询
const handleQuery = (val) => {
  user = val.value
  getUsersList()
}
// 重置
const handleReset = (val) => {
  message.message('重置成功!', 'success')
  getUsersList()
}


</script>

<style lang="scss" scoped>
.user-manager {
  .query-form {
    border-radius: 5px;
    background-color: #fff;
    padding: 20px;
    .el-form-item {
      margin-bottom: 0;
    }
  }
  .base-table {
    margin-top: 20px;
    border-radius: 5px;
  }
}
</style>